package com.example.fish.service.impl;

import com.example.fish.mapper.ChatMsgMapper;
import com.example.fish.mapper.LinkInfoMapper;
import com.example.fish.mapper.UserInfoMapper;
import com.example.fish.pojo.*;
import com.example.fish.service.WebSocketService;
import com.example.fish.vo.ResultMessage;
import com.example.fish.vo.UserChatInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class WebSocketServiceImpl implements WebSocketService {
    @Autowired
    private ChatMsgMapper chatMsgMapper;

    @Autowired
    private LinkInfoMapper linkInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /***
     *  保存消息到数据库
     */
    @Override
    public void saveMessage(Integer fromUserId, Integer targetUserid, String message) {
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setFromid(fromUserId);
        chatMsg.setTargetid(targetUserid);
        chatMsg.setMessage(message);
//        得到当前时候
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        chatMsg.setTime(formattedDateTime);
        chatMsg.setIslast(0);
//        保存
        chatMsgMapper.insertSelective(chatMsg);
    }

    @Override
    public List<ResultMessage> isFirstTalk(Integer fromUserId, Integer targetUserid) {
//        System.out.println("from userid"+fromUserId);
//        System.out.println("target userid"+targetUserid);
        LinkInfoExample example = new LinkInfoExample();
        example.createCriteria().andUser1idEqualTo(fromUserId).andUser2idEqualTo(targetUserid);
        int i = linkInfoMapper.countByExample(example);
        if (i == 0){
//            新建链接信息
            LinkInfo info = new LinkInfo();
            info.setUser1id(fromUserId);
            info.setUser2id(targetUserid);
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            info.setTime(formattedDateTime);
             linkInfoMapper.insert(info);
        }else {
//            查询所有聊天记录
//            System.out.println("查询最后十条数据"+fromUserId+" "+targetUserid);
            ChatMsgExample example1 = new ChatMsgExample();
            ChatMsgExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andTargetidEqualTo(targetUserid).andFromidEqualTo(fromUserId);
            ChatMsgExample.Criteria criteria2 = example1.createCriteria();
            criteria2.andFromidEqualTo(targetUserid).andTargetidEqualTo(fromUserId);
            example1.or(criteria2);
            example1.setOrderByClause("time ASC");
            List<ChatMsg> chatMsgList = chatMsgMapper.selectByExample(example1);
//            根据fromuserid 和targetUserid查询对应的信息
            UserInfo fromUser = userInfoMapper.selectByPrimaryKey(fromUserId);
            UserInfo targetUser = userInfoMapper.selectByPrimaryKey(targetUserid);
            List<ResultMessage> resultMessages = new ArrayList<>();
            if (chatMsgList.size() > 10){
//                查询最后10条消息
                for (int j = chatMsgList.size()-10; j < chatMsgList.size(); j++) {
                    ResultMessage resultMessage = new ResultMessage();
                    resultMessage.setTargetid(chatMsgList.get(j).getTargetid());
                    resultMessage.setMessage(chatMsgList.get(j).getMessage());
                    resultMessage.setFromid(chatMsgList.get(j).getFromid());
//                    截取时间
                    resultMessage.setTime(chatMsgList.get(j).getTime());
                    resultMessage.setUsername(targetUser.getName());
                    resultMessage.setFromAvatar(fromUser.getAvator());
                    resultMessage.setTargetAvatar(targetUser.getAvator());
                    resultMessages.add(resultMessage);
                }
                return resultMessages;
            }else {
//                查询全部
                for (ChatMsg chatMsg : chatMsgList) {
                    ResultMessage resultMessage = new ResultMessage();
                    resultMessage.setTargetid(chatMsg.getTargetid());
                    resultMessage.setFromid(chatMsg.getFromid());
                    resultMessage.setMessage(chatMsg.getMessage());
                    resultMessage.setFromAvatar(fromUser.getAvator());
                    resultMessage.setTargetAvatar(targetUser.getAvator());
                    resultMessage.setTime(chatMsg.getTime());
                    resultMessage.setUsername(targetUser.getName());
                    resultMessages.add(resultMessage);

                }
                return resultMessages;
            }
        }
        return null;
    }

    /***
     * 用来保存用户离线时的消息
     */
    @Override
    public void saveOfflineMessage(Integer fromUserId, Integer targetUserid, String message) {
//        封装信息
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setMessage(message);
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        chatMsg.setTime(formattedDateTime);
        chatMsg.setFromid(fromUserId);
        chatMsg.setTargetid(targetUserid);
//        保存消息
        chatMsgMapper.insert(chatMsg);
    }
    /***
     * 当用户登录时候，根据id查询targetid  且 islast  == 1 的信息
     * @param fromUserId  谁发送给当前登录用户的id
     * @param targetUserid  == 当前登录的用户id
     * @return
     */
    @Override
    public List<ResultMessage> getOfflineMessage(Integer targetUserid,Integer fromUserId) {
        ChatMsgExample example = new ChatMsgExample();
        example.createCriteria().andTargetidEqualTo(targetUserid).andIslastEqualTo(1);
        List<ChatMsg> chatMsgs = chatMsgMapper.selectByExample(example);
        List<ResultMessage> list = new ArrayList<>();

//        封装消息格式，并返回
        for (ChatMsg chatMsg : chatMsgs) {
            ResultMessage resultMessage = new ResultMessage();
            resultMessage.setMessage(chatMsg.getMessage());
            resultMessage.setFromid(chatMsg.getFromid());
            resultMessage.setTargetid(chatMsg.getTargetid());
            resultMessage.setTime(chatMsg.getTime());
            UserInfo target = userInfoMapper.selectById(chatMsg.getTargetid());
            resultMessage.setUsername(target.getName());
            resultMessage.setTargetAvatar(target.getAvator());
            UserInfo from = userInfoMapper.selectById(resultMessage.getFromid());
            resultMessage.setFromAvatar(from.getAvator());
            list.add(resultMessage);
        }
        return list;
    }
    /***
     * 删除离线消息
     * 别人发给我的未读消息，，fromid应该是别人，targeti是我 ，，
     * @param targetuserid 目前登录的id
     * @param fromuserid 从谁发来的id
     */
    @Override
    public void deleteOfflineMessage(Integer targetuserid,Integer fromuserid) {
        ChatMsgExample example = new ChatMsgExample();
        example.createCriteria().andTargetidEqualTo(targetuserid).andFromidEqualTo(fromuserid).andIslastEqualTo(1);
        List<ChatMsg> chatMsgs = chatMsgMapper.selectByExample(example);
        for (ChatMsg chatMsg : chatMsgs) {
            chatMsg.setIslast(0);
            chatMsgMapper.updateByPrimaryKey(chatMsg);
        }
    }

    /***
     * 统计个人信息页面的chat信息
     *先根据chatLink表查询聊天消息，---->targetId---->targetName,sex
     * lastTime  ==  两人的聊天记录且isLast == 0
     * count  ===  两人的聊天记录且isLast == 1 的数量
     * @param id 当前登录的id
     */
    @Override
    public List<UserChatInfo> getChatUser(Integer id) {
        LinkInfoExample example  = new LinkInfoExample();
        example.createCriteria().andUser1idEqualTo(id);
        List<LinkInfo> linkInfos = linkInfoMapper.selectByExample(example);
        List<UserChatInfo> list = new ArrayList<>();
        for (LinkInfo linkInfo : linkInfos) {
            UserChatInfo userChatInfo = new UserChatInfo();
            userChatInfo.setTargetid(linkInfo.getUser2id());
//            根据targetid查询相关name sex
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(linkInfo.getUser2id());
            userChatInfo.setTargetname(userInfo.getName());
            userChatInfo.setSex(userInfo.getSex());
//            根据双方的聊天记录查询 lastTime 和 count
            ChatMsgExample chatMsgExample= new ChatMsgExample();
            ChatMsgExample.Criteria criteria1 = chatMsgExample.createCriteria();
            criteria1.andTargetidEqualTo(id).andFromidEqualTo(linkInfo.getUser2id()).andIslastEqualTo(0);
            ChatMsgExample.Criteria criteria2 = chatMsgExample.createCriteria();
            criteria2.andFromidEqualTo(id).andTargetidEqualTo(linkInfo.getUser2id()).andIslastEqualTo(0);
            chatMsgExample.or(criteria2);
            chatMsgExample.setOrderByClause("time desc");
            List<ChatMsg> chatMsgs = chatMsgMapper.selectByExample(chatMsgExample);
            userChatInfo.setLasttime(chatMsgs.get(0).getTime());
//            查询count
            ChatMsgExample example1 = new ChatMsgExample();
            example1.createCriteria().andTargetidEqualTo(id).andFromidEqualTo(linkInfo.getUser2id()).andIslastEqualTo(1);
            int i = chatMsgMapper.countByExample(example1);
            userChatInfo.setCount(i);
            list.add(userChatInfo);

        }
        return list;
    }
}
